package com.lily.aidouzixun.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;

import com.lily.aidouzixun.R;
import com.lily.aidouzixun.interfacez.DetailJsInterface;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.MyWebView;
import com.lily.aidouzixun.ui.PullToRefreshView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.Validator;

import java.lang.ref.WeakReference;

/**
 * 自定义的WebViewFragment
 */
public class MyWebViewFragment  extends Fragment{
    private static final String TAG = "MyWebViewFragment";
    private PullToRefreshView pullToRefreshView;
    private ScrollView sv;
    private TitleBar mTitlebar;
    private ProgressBar mProgressBar;
    private MyWebView myWebView;

    private Activity mActivity;
    private Context mContext;
    private MyHandler mHandler;
    /**
     * WebView的url
     */
    private String url = "";
    private String title = "";  //Fragent标题
    private String backTitle = "";  //返回标题
    private boolean showBack = false;   //是否显示关闭
    private int action;	//用户行为，1-得到新数据;2-得到更多数据
    private String interfaceName;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        getIntentParam();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        View view = inflater.inflate(R.layout.webview_fragment, container, false);
        findViews(view);
        addJsInterface();
        setListeners();
        myWebView.startLoadUrl(url, null);
        return view;
    }

    /**
     * 初始化
     */
    private void init() {
        action = 1;
        mActivity = this.getActivity();
        mContext = this.getActivity();
        mHandler = new MyHandler(this);
    }

    /**
     * 得到Intent传递过来的数据
     */
    public void getIntentParam() {
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            url = bundle.getString(MyConstant.IntentKey.WEBVIEW_URL);
            if (!Validator.isEffective(url)) {
                finishActivity();
                return;
            }
            //拼接参数
            String urid = MyConfig.getUserId(mContext);
            String param = MyConstant.RequireParams.URID + "=" + urid;
            if (url.contains("?")) {
                url += "&" + param;
            } else {
                url += "?" +param;
            }
            title = bundle.getString(MyConstant.IntentKey.TITLE);
            backTitle = bundle.getString(MyConstant.IntentKey.BACK_TITLE);
            showBack = bundle.getBoolean(MyConstant.IntentKey.WEBVIEW_SHOWBACK);
            interfaceName = bundle.getString(MyConstant.IntentKey.WEBVIEW_INTERFACE);
        }
    }

    /**
     * 找到控件
     * @param view
     */
    @SuppressLint("JavascriptInterface")
    private void findViews(View view) {
        mTitlebar = (TitleBar) view.findViewById(R.id.tb_webview);
        mTitlebar.setCurActivity(mActivity);
        if (showBack) {
            mTitlebar.setLeftOperationVisible(true);
            if(Validator.isEffective(backTitle)) {
                mTitlebar.setLeftOperation(backTitle);
            }
        } else {
            mTitlebar.setLeftOperationVisible(false);
        }
        mTitlebar.setRightOperationVisibility(View.GONE);
        if (Validator.isEffective(title)) {
            mTitlebar.setTitle(title);
        }
        mProgressBar = (ProgressBar) view.findViewById(R.id.pb_webview);
        mProgressBar.setProgress(0);
        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.refreshable_view);
        pullToRefreshView.setNeedGetMoreData(true);
        pullToRefreshView.setNeedGetNewData(true);
        pullToRefreshView.setFootMode(PullToRefreshView.FootViewMode.ClickAble);
        pullToRefreshView.setOnRefreshListener(refreshListener);
        sv = (ScrollView) view.findViewById(R.id.sv);
        myWebView = (MyWebView) view.findViewById(R.id.webview);
        initWebView();
    }



    /**
     * 增加js通信接口
     */
    private void addJsInterface() {
        if (Validator.isEffective(interfaceName)) {
            if (WebViewConstans.InterfaceName.LONGDISTANCE_DETAIL .equals(interfaceName)) { //文章详情
                myWebView.addJavascriptInterface(new DetailJsInterface(mActivity), WebViewConstans.InterfaceName.LONGDISTANCE_DETAIL);
            }
        }
    }

    /**
     * 得到MyWebView对象
     * @return
     */
    public MyWebView getMyWebView() {
        return myWebView;
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //左边返回按钮的监听
        mTitlebar.setLeftOperationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myWebView.canGoBack()) {
                    myWebView.goBack();
                } else {
                    finishActivity();
                }
            }
        });
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        myWebView.setActivity(mActivity);
        myWebView.setContext(mContext);
        myWebView.setProgressBar(mProgressBar);
    }

    /**
     * 关闭Activity
     */
    private void finishActivity() {
        if (mActivity != null) {
            mActivity.finish();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            myWebView.stopLoading();
        } catch (Exception e) {
        }
    }

    public Handler getHandler() {
        return mHandler;
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Fragment> mFragmentReference;

        /**
         * 构造方法，传递fragment对象，防止内存泄露
         * @param fragment
         */
        MyHandler(Fragment fragment) {
            mFragmentReference = new WeakReference<Fragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final MyWebViewFragment fragment = (MyWebViewFragment) mFragmentReference.get();
                if(fragment !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.ON_KEY_DOWN:   //按下了物理返回键
                            fragment.mTitlebar.getLeftOperation().performClick();
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }

    PullToRefreshView.OnRefreshListener refreshListener = new PullToRefreshView.OnRefreshListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            action = 1;
            MessageDispatcher.sendMessage(MyWebView.getMyHandler(), MessageType.PULL_REFRESH);
            pullToRefreshView.onHeaderRefreshComplete();
            pullToRefreshView.onComplete(false);
        }

        @Override
        public boolean onMore(int nextPageNum) {
            // TODO Auto-generated method stub
            action = 2;
            return false;
        }

        @Override
        public void onGetPageData() {
            // TODO Auto-generated method stub
        }

    };


}
